import os
import logging
from datetime import datetime
from werkzeug.utils import secure_filename

# 配置日志
logger = logging.getLogger(__name__)

class FileUtils:
    def __init__(self, upload_folder, allowed_extensions):
        self.upload_folder = upload_folder
        self.allowed_extensions = allowed_extensions
        
    def allowed_file(self, filename):
        """检查文件类型是否允许"""
        return '.' in filename and filename.rsplit('.', 1)[1].lower() in self.allowed_extensions
        
    def save_uploaded_file(self, file, temp=False):
        """保存上传的文件
        Args:
            file: 上传的文件对象
            temp: 是否为临时文件
            
        Returns:
            (str, str): 返回文件路径和生成的文件名
        """
        try:
            filename = secure_filename(file.filename)
            base_name, extension = os.path.splitext(filename)
            
            if temp:
                filepath = os.path.join(self.upload_folder, filename)
            else:
                # 为非临时文件生成唯一文件名
                timestamp = datetime.now().strftime('%Y%m%d_%H%M%S')
                unique_filename = f"{extension[1:]}_{timestamp}{extension}"
                filepath = os.path.join(self.upload_folder, unique_filename)
                filename = unique_filename
            
            os.makedirs(self.upload_folder, exist_ok=True)
            file.save(filepath)
            logger.info(f"文件已保存: {filepath}")
            
            return filepath, filename
            
        except Exception as e:
            logger.error(f'保存文件失败: {str(e)}')
            raise
            
    def remove_file(self, filepath):
        """删除文件"""
        try:
            if os.path.exists(filepath):
                os.remove(filepath)
                logger.info(f"文件已删除: {filepath}")
        except Exception as e:
            logger.error(f"删除文件失败 {filepath}: {str(e)}")